#!/usr/bin/python
# -*- coding:utf-8 -*-
import numpy as np
import pandas as pd
import arcpy
import csv
import math

##################################################################
filepath = u"E:\\0S-lab\\0slab项目\\10襄阳\\multicenter\\out\\DBSCAN_100_20\\"

filenames = [u"all2008out.csv", u"all2015out.csv", u"all2017out.csv"]
clusternames = [u"all2008out_cluster.csv", u"all2015out_cluster.csv", u"all2017out_cluster.csv"]
centralnames = [u"all2008out_central.csv", u"all2015out_central.csv", u"all2017out_central.csv"]
finalnames = [u"all2008out_A.csv", u"all2015out_A.csv", u"all2017out_A.csv"]

##################################################################
arcpy.env.workspace = u"E:\\0S-lab\\0slab项目\\10襄阳\\DATA.gdb\\"
arcpy.env.overwriteOutput = True
arcpy.env.parallelProcessingFactor = "50%"
outdb = u"E:\\0S-lab\\0slab项目\\10襄阳\\DATA.gdb\\"
shppath = u"E:\\0S-lab\\0slab项目\\10襄阳\\testc\\"
shps = [u"all2008.shp", u"all2015.shp", u"all2017.shp"]

# 计算聚类中心点（质心）以及面积
##################################################################
print "正在计算聚类面积..."

for i in filenames:
    f = open(filepath + i)
    tb = pd.read_csv(f)
    f.close()

    # cluster
    pt = pd.pivot_table(tb, index= "cluster", values= ["id","x","y"],aggfunc = {"x":'mean',"y":'mean', "id": 'count'})
    pt.reset_index(inplace=True)
    pt.rename(columns = {"id":"count"}, inplace = True)
    pt["area"] = pt["count"] * 900 /10000
    pt.to_csv(filepath + i.split(".csv")[0] + "_cluster.csv", index=None)

print "聚类面积计算完成"

# 提取中心点坐标（平均中心）
##################################################################
print "正在计算聚类中心..."

# 将shp转为feature class
# # TODO(WINGS): try...catch...
# for i in shps:
#     if not arcpy.Exists(shppath + i):
#         print u"原始路径不存在该数据" + i
#         break
#     else:
#         a = arcpy.Exists(outdb + i.split(".shp")[0])
#         if arcpy.Exists(outdb + i.split(".shp")[0]):
#             arcpy.DeleteFeatures_management(outdb + i.split(".shp")[0])
#             print u"正在删除" + outdb + i.split(".shp")[0]
#         arcpy.FeatureClassToFeatureClass_conversion(shppath + i, outdb, i.split(".shp")[0])
#         print "正在将shp转换为要素集..."
#
# # 将csv转为表
# intable = []
# for i in filenames:
#     if not arcpy.Exists(filepath + i):
#         print u"原始路径不存在表格" + i
#         break
#     else:
#         if arcpy.Exists(outdb + i.split(".csv")[0]):
#             arcpy.Delete_management(outdb + i.split(".csv")[0])
#         intable.append(filepath + i)
# print "正在将csv转换为表..."
# arcpy.TableToGeodatabase_conversion(Input_Table=intable, Output_Geodatabase=outdb)


# # 取中心点
# for i in range(0, len(shps)):
#     infeature = outdb + shps[i].split(".shp")[0]
#     intable = outdb + filenames[i].split(".csv")[0]
#     print "正在连接字段..."
#     # arcpy.MakeFeatureLayer_management(infeature, infeature+u"_layer")
#     # arcpy.AddJoin_management(in_layer_or_view=infeature+u"_layer", in_field=u"ID", join_table=intable, join_field=u"id", join_type="KEEP_COMMON")
#     arcpy.JoinField_management(infeature, "ID", intable, "id", "cluster")
#     outcentral = outdb + filenames[i].split(".csv")[0]+"_central"
#     print "正在取中心点..."
#     arcpy.CentralFeature_stats(infeature, outcentral, "EUCLIDEAN_DISTANCE", "#", "#", "cluster")
#
#
#     # TODO(Wings) Use pandas instead
#     print 'Export attributes table...'
#     csvFileName = filepath + centralnames[i]
#     writeFile = open(csvFileName, "wb")
#     writeFileHandle = csv.writer(writeFile)
#     outputHeader = ['cluster', 'POINT_X', 'POINT_Y']
#     writeFileHandle.writerow(outputHeader)
#     searchCur = arcpy.SearchCursor(outcentral)
#     for row in searchCur:
#         outputMatrix = []
#         outputMatrix.append(row.getValue('cluster'))
#         outputMatrix.append(row.getValue('Point_X'))
#         outputMatrix.append(row.getValue('Point_Y'))
#         writeFileHandle.writerow(outputMatrix)
#     writeFile.close()
#     del row
#     del searchCur
#     print '写入cental表完成!'
#
# print "聚类中心计算完成..."
#
# # 合并表
# ##################################################################
# print "正在合并表..."
#
# for i in range(0, len(filenames)):
#     f1 = open(filepath + clusternames[i])
#     f2 = open(filepath + centralnames[i])
#     t1 = pd.read_csv(f1)
#     t2 = pd.read_csv(f2)
#     A = pd.merge(t1, t2, how="left", on=['cluster'])
#     A.to_csv(filepath + finalnames[i])
#
# print "表格合并完成..."

# 计算距离矩阵
##################################################################
print "正在计算距离矩阵..."

for k in finalnames:
    f = open(filepath + k)
    df = pd.read_csv(f)
    f.close()

    # compute matrix
    n = df.shape[0]
    mat = np.zeros((n, n))
    for i in range(0, n):
        for j in range(0, n):
            if i == j:
                mat[i][j] = 0
            else:
                # [x1, y1] = df["Point_X"][i], df["Point_Y"][i]
                [x1, y1] = df["x"][i], df["y"][i]
                area1 = df["area"][i]
                # [x2, y2] = df["Point_X"][j], df["Point_Y"][j]
                [x2, y2] = df["x"][j], df["y"][j]
                area2 = df["area"][j]
                temp = math.sqrt((x1 - x2)**2 + (y1 - y2)**2)
                mat[i][j] = area1 * area2 / temp
    outname = filepath + k.split(".csv")[0] + '_mat.txt'
    np.savetxt(outname, mat, delimiter=' ', fmt="%.10f")

print "距离矩阵计算完成..."
print "计算结束。"